<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
    width: 100px;
    height: 100px;
    background-color: lightblue;
    position: absolute;
    left: 10px;
    top: 10px;
}
</style>
</head>
<body>

<div class="box"></div>


<script>
var box = document.querySelector('.box');

box.onmousedown = function (e){
    var ofsetx = e.offsetX;// 鼠标按下位置到box左边的距离
    var ofsety = e.offsetY;// 鼠标按下位置到box顶部的距离
    document.onmousemove = function (e){
        var l = e.pageX - ofsetx;// box定位left值
        var t = e.pageY - ofsety;// box定位top值

        // 修改box的定位值
        box.style.left = l + 'px';
        box.style.top = t + 'px';
    }
    box.onmouseup = function (){
        document.onmousemove = null;// 移除事件
    }
}

// 练习：将box限制在可视区内拖拽

</script>
</body>
</html>